import json
import logging
import time

from robot.result.model import TestCase as TestCaseResult
from robot.running.model import TestCase as TestCaseModel

logger = logging.getLogger("ZTestRunnerAgent")

VAR_ZCM_PRE_DRYRUN = 'zcmpredryrun'


def is_dict(log_content):
    """
    能否转成字典
    :param log_content:
    :return:
    """
    try:
        eval(log_content)
    except:
        return False
    return True


class ZTestRunnerAgent:
    """
    ZCM 自定义Test Listener
    -v zcmpredryrun 开启dryrun时， runner只统计total值，不上报
    """
    ROBOT_LISTENER_API_VERSION = 3

    _RUNNING = 0
    _FINISHED = 1

    def __init__(self):
        pass

    def start_suite(self, data, _):
        pass

    def end_suite(self, data, result):
        pass

    def start_test(self, data, _):
        pass

    def end_test(self, data:TestCaseModel, test_case: TestCaseResult):
        logger.info("data.keywords  {}".format(data.keywords))
        caseMsg = {'path': test_case.longname, 'loganchor': test_case.id}
        if is_dict(test_case.message):
            caseMsg.update(eval(test_case.message))
        else:
            caseMsg.update({'msg':test_case.message})
        # with open('E:/test.txt', 'a+') as f:
        #     f.write('{}\n'.format(caseMsg))
        #     f.write("data.keywords  {}\n".format(data.keywords))
        #     for keyword in data.keywords:
        #         f.write('name {0} args{1} {2}\n'.format(keyword.name, keyword.args, type(keyword.args)))
    def close(self):
        pass
